package com.etv.launcher.common.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.VectorDrawable;
import android.os.Build;

import androidx.core.graphics.ColorUtils;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
import androidx.annotation.NonNull;
import androidx.palette.graphics.Palette;

import java.lang.reflect.Method;

public class ColorUtil {

    private static final int DEFAULT_BACKGROUND = Color.GREEN;

    public static int getPrimaryColor(@NonNull Drawable iconDrawable) {
        Bitmap iconBitmap = drawableToBitmap(iconDrawable);
        if (iconBitmap == null) {
            return Color.RED;
        }

        return getDominantColor(iconBitmap);
    }

    public static int generateBackgroundFromColor(int iconColor) {
        // 转换到LAB颜色空间（更符合人眼感知）
        double[] lab = new double[3];
        ColorUtils.colorToLAB(iconColor, lab); // lab[0]=L*, lab[1]=a*, lab[2]=b*

        // 调整参数（关键优化点）
        double newL = Math.max(lab[0] - 35, 25);  // 亮度降低35单位，最低25
        double newA = lab[1] * 0.4;              // 降低a轴强度
        double newB = lab[2] * 0.5;              // 降低b轴强度

        newL = Math.min(Math.max(newL, 0), 100); // 强制限制L范围
        newA = Math.min(Math.max(newA, -128), 127);
        newB = Math.min(Math.max(newB, -128), 127);


        // 转换回RGB颜色
        int baseColor = ColorUtils.LABToColor(newL, newA, newB);

        // 叠加暗色基底（#333333）增强质感
        return ColorUtils.blendARGB(baseColor, 0xFF333333, 0.25f);
    }

    /**
     * 转换drawable为bitmap
     *
     * @param drawable
     * @return
     */
    private static Bitmap drawableToBitmap(@NonNull Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof VectorDrawable || drawable instanceof VectorDrawableCompat) {
            return renderGenericDrawable(drawable);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (drawable instanceof AdaptiveIconDrawable) {
                return renderAdaptiveIcon(drawable);
            }
        }
        return null;
    }

    private static Bitmap renderGenericDrawable(Drawable drawable) {
        // 保证最小渲染尺寸
        int width = Math.max(drawable.getIntrinsicWidth(), 256);
        int height = Math.max(drawable.getIntrinsicHeight(), 256);

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        // 启用高质量渲染
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        paint.setDither(true);

        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }

    private static Bitmap renderAdaptiveIcon(Drawable drawable) {
        try {
            // 通过反射获取自适应图标的前景/背景
            Drawable foreground = (Drawable) invokeMethod(drawable, "getForeground");
            Drawable background = (Drawable) invokeMethod(drawable, "getBackground");

            // 创建合并图层
            int size = 512; // 高清渲染
            Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);

            // 绘制背景层
            background.setBounds(0, 0, size, size);
            background.draw(canvas);

            // 绘制前景层（应用图标主体）
            foreground.setBounds(0, 0, size, size);
            foreground.draw(canvas);

            return bitmap;
        } catch (Exception e) {
            return renderGenericDrawable(drawable);
        }
    }

    private static Object invokeMethod(Object obj, String methodName) throws Exception {
        Method method = obj.getClass().getMethod(methodName);
        return method.invoke(obj);
    }


    private static int getDominantColor(Bitmap bitmap) {
        Palette palette = Palette.from(bitmap)
                .clearFilters()
                .generate();
        return palette.getVibrantColor(palette.getDominantColor(DEFAULT_BACKGROUND));
    }
}